AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')

util.PrecacheSound( "eli_lab.firebell_loop_1" )
util.PrecacheSound( "Buttons.snd5" )

local Energy_Increment = 50
local SellAmount = { easy = 1000 , medium = 250 , hard = 100 , tough = 10 }

function ENT:Initialize()
    self.BaseClass.Initialize(self)

    local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(300)
	end
	
	self.tink = 0
	self.notinit = false
	self.SM = CAF.GetAddon("Selling Machine")
	self.mute = 0
	
	if not (WireAddon == nil) then
		self.WireDebugName = self.PrintName
		local outs = {"Change"}
		for k, v in pairs(self.SM.resources) do
			table.insert(outs , k)
		end
		self.Inputs = WireLib.CreateInputs(self.Entity, { "Mute" })
		self.Outputs = WireLib.CreateOutputs(self.Entity, outs)
	end
	self:UpdateOutputPrices()
end

function ENT:UpdateOutputPrices()
	local changed = false
	self.SM = CAF.GetAddon("Selling Machine")
	for k, v in pairs(self.SM.resources) do
		if (self.Outputs[k].Value != v.value * (v.marked / 100)) then changed = true end
		if not (WireAddon == nil) then Wire_TriggerOutput(self.Entity, k, v.value * (v.marked / 100)) end
	end
	if (changed && self.notinit) then
		if not (WireAddon == nil) then Wire_TriggerOutput(self.Entity, "Change", 1) end
		if ( not(self.mute > 0) ) then
			self:EmitSound("eli_lab.firebell_loop_1")
			timer.Create( "ent_remBell"..tostring(self:EntIndex()), 3, 1, function()
				self:StopSound("eli_lab.firebell_loop_1")
				self:EmitSound("Buttons.snd5")
			end )
		end
	end
	if (not self.notinit) then self.notinit = true end
end


function ENT:TriggerInput(iname, value)
	if (iname == "Mute") then
		self.mute = value
	end
end

function ENT:OnRemove()
    self.BaseClass.OnRemove(self)
	self:StopSound("eli_lab.firebell_loop_1")
	timer.Remove("ent_remBell"..tostring(self:EntIndex()))
end

function ENT:Destruct()
	if CAF and CAF.GetAddon("Life Support") then
		CAF.GetAddon("Life Support").Destruct( self.Entity, false )
	end
end

function ENT:Think()
	self.BaseClass.Think(self)
	if (CurTime() >= (self.tink+1)) then
		if not (WireAddon == nil) then
			if (self.Outputs.Change.Value > 0) then
				Wire_TriggerOutput(self.Entity, "Change", 0)
			end
		end
		self:UpdateOutputPrices()
		self.tink = CurTime()
	end
end


